package com.example.Servlet;

import com.example.Service.NewsService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LikeNewsServlet", value = "/LikeNewsServlet")
public class LikeNewsServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型和编码
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        String newsId = request.getParameter("newsId");
        String action = request.getParameter("action"); // like 或 unlike
        Map<String, Object> result = new HashMap<>();

        try {
            if (newsId == null || newsId.trim().isEmpty()) {
                result.put("code", 400);
                result.put("msg", "新闻ID不能为空");
            } else {
                // 调用Service层更新点赞数
                NewsService newsService = new NewsService();
                boolean success;


                if ("unlike".equals(action)) {
                    // 取消点赞
                    success = newsService.decrementLikes(Integer.parseInt(newsId));
                } else {
                    // 点赞
                    success = newsService.incrementLikes(Integer.parseInt(newsId));
                }
                if (success) {
                    result.put("code", 200);
                    result.put("msg", "点赞成功");
                } else {
                    result.put("code", 500);
                    result.put("msg", "点赞失败");
                }
            }

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "服务器错误: " );

        }

        // 返回JSON响应
        Gson gson = new Gson();
        response.getWriter().write(gson.toJson(result));
    }
}